package com.library.infrastructure;

import org.springframework.stereotype.Service;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

@Service
public class CoverGeneratorService {

    public InputStream generateCover(String title, String author) throws Exception {
        int width = 500;
        int height = 700;

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bufferedImage.createGraphics();

        // 设置背景颜色
        g2d.setColor(new Color(200, 200, 200));
        g2d.fillRect(0, 0, width, height);

        // 设置字体
        Font titleFont = new Font("Arial", Font.BOLD, 40);
        Font authorFont = new Font("Arial", Font.PLAIN, 30);

        // 绘制标题
        g2d.setColor(Color.BLACK);
        g2d.setFont(titleFont);
        drawWrappedString(g2d, title, 50, 200, width - 100);

        // 绘制作者
        g2d.setFont(authorFont);
        g2d.drawString("by " + author, 50, height - 100);

        g2d.dispose();

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", os);
        return new ByteArrayInputStream(os.toByteArray());
    }

    private void drawWrappedString(Graphics2D g, String text, int x, int y, int maxWidth) {
        FontMetrics fm = g.getFontMetrics();
        String[] words = text.split("\\s+");
        String line = "";
        for (String word : words) {
            if (fm.stringWidth(line + word) < maxWidth) {
                line += word + " ";
            } else {
                g.drawString(line, x, y);
                y += fm.getHeight();
                line = word + " ";
            }
        }
        g.drawString(line, x, y);
    }
}